import * as apis from 'services/goodsTheme'

function parseJson(str) {
  if (str && typeof str === 'string') {
    return JSON.parse(str)
  }
  return str
}

const types = {
  GET_GOODSTHEME_BY_ID_SUCCESS: 'GET_GOODSTHEME_BY_ID_SUCCESS',
  GET_GOODSTHEME_BY_ID_FAILURE: 'GET_GOODSTHEME_BY_ID_FAILURE',
  GET_GOODSTHEME_BODY_SUCCESS: 'GET_GOODSTHEME_BODY_SUCCESS',
  GET_GOODSTHEME_BODY_FAILURE: 'GET_GOODSTHEME_BODY_FAILURE',
}

const state = {
  themInfoRow: {
    body: [],
  },
  pageLoading: true,
  currentPage: 1,
}

const getters = {
  content: state => parseJson(state.themInfoRow.body),
  title: state => state.themInfoRow.title,
  bgColor: state => state.themInfoRow.bgColor,
  pageLoading: state => state.pageLoading,
  currentPage: state => state.currentPage,
}

const actions = {
  getThemeInfoById({ commit }, id) {
    return apis.getThemeInfoById(id)
      .then((res) => {
        commit(types.GET_GOODSTHEME_BY_ID_SUCCESS, res)
        return res.data
      })
  },

  getThemeInfoBody({ commit }, payload) {
    return apis.getThemeInfoBody(payload)
      .then((res) => {
        commit(types.GET_GOODSTHEME_BODY_SUCCESS, res.data)
        return res.data
      })
  },
}

const mutations = {
  [types.GET_GOODSTHEME_BY_ID_SUCCESS](state, res) {
    state.themInfoRow = res.data
    if (!state.themInfoRow.body) {
      state.themInfoRow.body = []
    }
    state.pageLoading = false
  },

  [types.GET_GOODSTHEME_BY_ID_FAILURE](state, res) {
    state.themInfoRow = res.info
    state.pageLoading = false
  },

  [types.GET_GOODSTHEME_BODY_SUCCESS](state, data) {
    state.themInfoRow.body = state.themInfoRow.body.concat(data.data)
    state.currentPage = data.current_page
  },
}

export default {
  state,
  getters,
  actions,
  mutations,
}
